<template>
  <!-- 整体资料与配置 开始 -->
  <div :class="['TUI-profile', !isPC && 'TUI-profile-h5']">
	  
	<!-- 设置 开始 -->
    <div
      v-if="displayType !== 'setting'"
      :class="['TUI-profile-basic', !isPC && 'TUI-profile-h5-basic']"
    >
	  <!-- 头像  不嵌套 div 那个 click 事件不好用 哈哈 -->
	  <div @click="UpdateAvatarShow(true)">
		<img
        :class="[
          'TUI-profile-basic-avatar',
          !isPC && 'TUI-profile-h5-basic-avatar',
        ]"
        :src="
          userProfile.avatar ||
            'https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png'
        "
        >  
	  </div>
      
	  <!-- 用户ID 用户昵称 -->
      <div
        :class="[
          'TUI-profile-basic-info',
          !isPC && 'TUI-profile-h5-basic-info',
        ]"
      >
        <div
          :class="[
            'TUI-profile-basic-info-nick',
            !isPC && 'TUI-profile-h5-basic-info-nick',
          ]"
		  @click="UpdateNickShow(true)"
        >
          {{ userProfile.nick || "---设置昵称--" }}
        </div>
        <div
          :class="[
            'TUI-profile-basic-info-id',
            !isPC && 'TUI-profile-h5-basic-info-id',
          ]"
        >
          <label
            :class="[
              'TUI-profile-basic-info-id-label',
              !isPC && 'TUI-profile-h5-basic-info-id-label',
            ]"
          >{{ "用户ID" }}:</label>
          <div
            :class="[
              'TUI-profile-basic-info-id-value',
              !isPC && 'TUI-profile-h5-basic-info-id-value',
            ]"
          >
            {{ userProfile.userID }}
          </div>
        </div>
      </div>
    </div>
	<!-- 设置 结束 -->
	
	<!-- 资料展示 开始 -->
    <div
      v-if="displayType !== 'profile' && (!isPC || showSetting)"
      ref="settingDomRef"
      :class="['TUI-profile-setting', !isPC && 'TUI-profile-h5-setting']"
    >
	  <!-- 遍历 设置资料 -->
      <div
        v-for="(item, key) in settingList"
        :key="key"
        :class="[
          'TUI-profile-setting-item',
          !isPC && 'TUI-profile-h5-setting-item',
          item.value === 'exit' && 'TUI-profile-h5-setting-item-exit',
        ]"
      >
        <div
          :class="[
            'TUI-profile-setting-item-label',
            !isPC && 'TUI-profile-h5-setting-item-label',
          ]"
          @click="handleSettingListItemOnClick(item)"
        >
          <div :class="['label-left']">
            <div :class="['label-title']">
              {{ item.label }}
            </div>
            <div
              v-if="
                item.children && !isPC && item.childrenShowType === 'switch'
              "
              :class="['label-desc']"
            >
              {{ item.value }}
            </div>
          </div>
          <div :class="['label-right']">
            <div
              v-if="
                !isPC &&
                  item.children &&
                  item.selectedChild &&
                  item.childrenShowType === 'bottomPopup'
              "
              :class="[
                'TUI-profile-setting-item-label-value',
                !isPC && 'TUI-profile-h5-setting-item-label-value',
              ]"
            >
              {{ generateLabel(item) }}
            </div>
            <Icon
              v-if="item.children"
              :file="rightArrowIcon"
              width="14px"
              height="14px"
              style="width: 14px; height: 14px; display: flex"
            />
          </div>
        </div>
        <!-- 移动端 children显示，分多个类型 -->
        <BottomPopup
          v-if="
            item.children && !isPC && item.childrenShowType === 'bottomPopup'
          "
          :show="item.showChildren"
          @onClose="bottomPopupOnClose(item)"
        >
          <div
            v-for="child in item.children"
            :class="[
              'TUI-profile-setting-item-bottom-popup',
              !isPC && 'TUI-profile-h5-setting-item-bottom-popup',
            ]"
            @click="handleSettingListItemOnClick(child)"
          >
            {{ child.label }}
          </div>
        </BottomPopup>
		
		<!-- 更新昵称 -->
		<Dialog 
		  :show="isShowNickDialog"
		  @submit="submitNick"
		  @update:show="close"
		>
			<input v-model="nick" focus placeholder="请输入昵称" />
		</Dialog>
		
		<!-- 更新头像 -->
		<Dialog 
		  :show="isShowAvatarDialog"
		  @submit="submitAvatar"
		  @update:show="close"
		>
		  <uni-file-picker 
		  	v-model="avatarImg"  
		  	file-mediatype="image"
		  	mode="grid"
		  	file-extname="png,jpg"
		  	:limit="1"
		  	@progress="progress" 
		  	@success="success" 
		  	@fail="fail" 
		  	@select="select"
		  />
		</Dialog>
		
		<!-- 修改密码 -->
		<Dialog 
		  :show="isShowPwdDialog"
		  @submit="submitPwd"
		  @update:show="close"
		>
		  <ul>
			  <li><input v-model="pwd_old" focus placeholder="请输入旧密码" /></li>
			  <li><input v-model="pwd_new" focus placeholder="请输入新密码" /></li>
			  <li><input v-model="pwd_re" focus placeholder="请重复输入新密码" /></li>
		  </ul>
		</Dialog>
		
      </div>
    </div>
	<!-- 资料展示 结束 -->
	
  </div>
</template>
<script lang="ts" setup>
import TUIChatEngine, {
  TUIUserService,
  TUIStore,
  StoreName,
  TUIChatService,
} from '@tencentcloud/chat-uikit-engine';
import { TUITranslateService } from '@tencentcloud/chat-uikit-engine';
import { TUILogin } from '@tencentcloud/tui-core';
import { TUIGlobal } from '@tencentcloud/universal-api';
import { ref, defineProps, onMounted } from '/TUIKit/adapter-vue';
import { isPC } from '/TUIKit/utils/env';
import { Toast, TOAST_TYPE } from '/pages/common/Toast/index';
import BottomPopup from '/pages/common/BottomPopup/index.vue';
import Dialog from '/pages/common/Dialog/index.vue';
import Icon from '/pages/common/Icon.vue';
import rightArrowIcon from '/TUIKit/assets/icon/right-icon.svg';
import { IUserProfile } from '/TUIKit/interface';
import { onHide } from '@dcloudio/uni-app';
import { translator } from '/pages/chat/utils/translation';
import { removeTokenStorage } from '/utils/token';

const props = defineProps({
  displayType: {
    type: String,
    default: 'all', // "profile"/"setting"/"all"
  },
  showSetting: {
    type: Boolean,
    default: false,
  },
});

// 编辑对话框
const isShowNickDialog = ref(false);
const nick = ref();

const isShowAvatarDialog = ref(false);
const avatarImg = ref();
const avatarImgUrl = ref();

const isShowPwdDialog = ref(false);
const pwd_old = ref();
const pwd_new = ref();
const pwd_re = ref();

const settingDomRef = ref();
const userProfile = ref<IUserProfile>({});
const settingList = ref<{
  [propsName: string]: {
    value: string;
    label: string;
    onClick?: any;
    // children相关
    selectedChild?: string;
    childrenShowType?: string; // "bottomPopup"/"switch"
    showChildren?: boolean;
    children?: {
      [propsName: string]: {
        value: string;
        label: string;
        onClick?: any;
      };
    };
  };
}>({
  editPwd: {
    value: 'editPwd',
    label: '修改密码',
    onClick: (item: any) => {
  	  isShowPwdDialog.value = true;
    },
  },
  faxian: {
    value: 'faxian',
    label: '发现',
    onClick: (item: any) => {
  	  uni.navigateTo({
  	  	url:'/pages/views/faxian'
  	  })
    },
  },
  allowType: {
    value: 'allowType',
    label: '加我为好友时',
    selectedChild: '',
    childrenShowType: 'bottomPopup',
    showChildren: false,
    onClick: (item: any) => {
      if (!isPC) {
        item.showChildren = true;
      }
    },
    children: {
      [TUIChatEngine.TYPES.ALLOW_TYPE_ALLOW_ANY]: {
        value: TUIChatEngine.TYPES.ALLOW_TYPE_ALLOW_ANY,
        label: '同意任何用户加好友',
        onClick: (item: any) => {
          updateMyProfile({ allowType: item.value });
        },
      },
      [TUIChatEngine.TYPES.ALLOW_TYPE_NEED_CONFIRM]: {
        value: TUIChatEngine.TYPES.ALLOW_TYPE_NEED_CONFIRM,
        label: '需要验证',
        onClick: (item: any) => {
          updateMyProfile({ allowType: item.value });
        },
      },
      [TUIChatEngine.TYPES.ALLOW_TYPE_DENY_ANY]: {
        value: TUIChatEngine.TYPES.ALLOW_TYPE_DENY_ANY,
        label: '拒绝任何人加好友',
        onClick: (item: any) => {
          updateMyProfile({ allowType: item.value });
        },
      },
    },
  },
  displayMessageReadReceipt: {
    value: 'displayMessageReadReceipt',
    label: '消息阅读状态',
    selectedChild: 'userLevelReadReceiptOpen',
    childrenShowType: 'bottomPopup',
    showChildren: false,
    onClick(item: any) {
      if (!isPC) {
        item.showChildren = true;
      }
    },
    children: {
      userLevelReadReceiptOpen: {
        value: 'userLevelReadReceiptOpen',
        label: '开启',
        onClick() {
          switchEnabelUserLevelReadRecript(true);
        },
      },
      userLevelReadReceiptClose: {
        value: 'userLevelReadReceiptClose',
        label: '关闭',
        onClick() {
          switchEnabelUserLevelReadRecript(false);
        },
      },
    },
  },
  displayOnlineStatus: {
    value: 'displayOnlineStatus',
    label: '显示在线状态',
    selectedChild: 'userLevelOnlineStatusOpen',
    childrenShowType: 'bottomPopup',
    showChildren: false,
    onClick(item: any) {
      if (!isPC) {
        item.showChildren = true;
      }
    },
    children: {
      userLevelOnlineStatusOpen: {
        value: 'userLevelOnlineStatusOpen',
        label: '开启',
        onClick() {
          switchUserLevelOnlineStatus(true);
        },
      },
      userLevelOnlineStatusClose: {
        value: 'userLevelOnlineStatusClose',
        label: '关闭',
        onClick() {
          switchUserLevelOnlineStatus(false);
        },
      },
    },
  },
  translateLanguage: {
    value: 'translateLanguage',
    label: '翻译语言',
    selectedChild: 'zh',
    childrenShowType: 'bottomPopup',
    showChildren: false,
    onClick(item: any) {
      if (!isPC) {
        item.showChildren = true;
      }
    },
    children: {
      zh: {
        value: 'zh',
        label: '中文',
        onClick() {
          switchTranslationTargetLanguage('zh');
        },
      },
      en: {
        value: 'en',
        label: 'English',
        onClick() {
          switchTranslationTargetLanguage('en');
        },
      },
      jp: {
        value: 'jp',
        label: '日本語',
        onClick() {
          switchTranslationTargetLanguage('jp');
        },
      },
      kr: {
        value: 'kr',
        label: '한국인',
        onClick() {
          switchTranslationTargetLanguage('kr');
        },
      },
    },
  },
  switchAudio: {
    value: 'switchAudio',
    label: '消息音效',
    selectedChild: 'open',
    childrenShowType: 'bottomPopup',
    showChildren: false,
    onClick(item: any) {
      if (!isPC) {
        item.showChildren = true;
      }
    },
    children: {
      open: {
        value: 'open',
        label: '开启',
        onClick() {
          switchAudioFn('open');
        },
      },
      close: {
        value: 'close',
        label: '关闭',
        onClick() {
          switchAudioFn('close');
        },
      },
    },
  },
  exit: {
    value: 'exit',
    label: '退出登录',
    onClick: (item: any) => {
	  try{
		TUILogin.logout().then(() => {});
	  } catch (e) {
	  	// error
	  }
	  // 普通 h5 清理
	  try {
	  	uni.removeStorageSync('userTencentID');
	  } catch (e) {
	  	// error
	  }
	  // 微信小程序里面 清理缓存
	  removeTokenStorage();
	  // 跳转页面
	  uni.navigateTo({
	  	url:'/pages/views/login'
	  })
    },
  },
});

// 音频开关
const switchAudioFn = (item:any) => {
	uni.setStorageSync('switchAudio',item)
	settingList.value.switchAudio.selectedChild = item;
	// 关闭展示
	settingList.value.switchAudio.showChildren = false;
}

// 显示弹窗 昵称
const UpdateNickShow = (item: any) => {
	isShowNickDialog.value = true
};

// 显示弹窗 头像
const UpdateAvatarShow = (item: any) => {
	isShowAvatarDialog.value = true
};

// 编辑资料 确认操作
const submitNick = () => {
	isShowNickDialog.value = false
	if(nick.value != ''){
	  updateMyProfile({ nick: nick.value });
	}
}

// 更新头像
const submitAvatar = () => {
	isShowAvatarDialog.value = false
	if(avatarImgUrl.value != ''){
	  updateMyProfile({ avatar: avatarImgUrl.value });
	}
}

// 更新密码
const submitPwd = () => {
	isShowPwdDialog.value = false
	if(pwd_new.value != '' && pwd_old.value != '' && pwd_re.value != ''){
	  // 更新 todo
	}
}

// 关闭弹窗
const close = () => {
	isShowNickDialog.value = false
	isShowAvatarDialog.value = false
	isShowPwdDialog.value = false
}

// 自动文件上传 处理过程
const progress = (option) => {
	console.log(option)
}
// 自动文件上传 成功
const success = (option) => {
	console.log(option)
}
// 自动文件上传 失败
const fail = (option) => {
	console.log(option)
}
// 自动文件上传 选择
const select = (option) => {
	// console.log(option)
	let base_url = uni.$baseUrl
	uni.uploadFile({
		url: base_url+'/home/user/uploads', // 仅为示例，非真实的接口地址
		filePath: option.tempFilePaths[0],
		name: 'file',
		header:{
			"X-Csrf-Token":uni.getStorageSync('token')
		},
		formData: {
			// user: 'test'
		},
		success: (res) => {
			let data = JSON.parse(res.data)
			avatarImgUrl.value = base_url+data.data
			updateMyProfile({ avatar: avatarImgUrl.value });
		}
	});
}

// 处理 点击事件 默认条目的 
const handleSettingListItemOnClick = (item: any) => {
  if (item?.onClick && typeof item?.onClick === 'function') {
    item.onClick(item);
  }
};

// 关闭弹出框
const bottomPopupOnClose = (item: any) => {
  item.showChildren = false;
};

// 创建标签 进行展示
const generateLabel = (item: any) => {
  return item?.children[item?.selectedChild]?.label;
};

// 自定义 更新用户资料 函数 利用接口实现
const updateMyProfile = (props: object) => {
  TUIUserService.updateMyProfile(props)
    .then((res: any) => {
      Toast({
        message: '更新用户资料成功',
        type: TOAST_TYPE.SUCCESS,
        duration: 0,
      });
      if ('allowType' in props) {
        settingList.value['allowType'].showChildren = false;
      }
    })
    .catch((err: any) => {
      console.warn('更新用户资料失败', err);
      Toast({
        message: '更新用户资料失败',
        type: TOAST_TYPE.ERROR,
        duration: 0,
      });
    });
};

// 监控用户资料编辑
TUIStore.watch(StoreName.USER, {
  // 显示用户基本信息
  userProfile: (userProfileData: IUserProfile) => {
    userProfile.value = userProfileData;
    if (userProfile?.value?.allowType) {
      settingList.value.allowType.selectedChild = userProfile?.value?.allowType;
    }
  },
  // 显示消息已读状态设置
  displayMessageReadReceipt(isDisplay: boolean) {
    settingList.value.displayMessageReadReceipt.selectedChild
      = isDisplay ? 'userLevelReadReceiptOpen' : 'userLevelReadReceiptClose';
  },
  // 显示在线状态设置
  displayOnlineStatus(isOnlineStatusDisplay: boolean) {
    settingList.value.displayOnlineStatus.selectedChild = isOnlineStatusDisplay
      ? 'userLevelOnlineStatusOpen'
      : 'userLevelOnlineStatusClose';
  },
});

// 规避TUIStore.watch userProfile 登录后暂时不能及时触发更新
onMounted(() => {
  // 查询自己的资料
  TUIUserService.getUserProfile().then((res: any) => {
    userProfile.value = res.data;
  });
});

// tabbar 切换其他tab，关闭profile已经打开的设置弹窗 | 
onHide(() => {
  for (const settingItemKey in settingList.value) {
    if (settingList?.value[settingItemKey]?.hasOwnProperty('showChildren')) {
      settingList.value[settingItemKey].showChildren = false;
    }
  }
});

// 设置 消息阅读状态
function switchEnabelUserLevelReadRecript(status: boolean) {
  // 更新状态到服务器
  TUIStore.update(StoreName.USER, 'displayMessageReadReceipt', status);
  // 关闭展示
  settingList.value['displayMessageReadReceipt'].showChildren = false;
}

// 设置用户在线状态 展示与否
function switchUserLevelOnlineStatus(status: boolean) {
  // 更新状态
  TUIUserService.switchUserStatus({ displayOnlineStatus: status });
  // 关闭展示
  settingList.value['displayOnlineStatus'].showChildren = false;
}

// 设置翻译 目标语言
function switchTranslationTargetLanguage(lang: string) {
  // 清理翻译 设置
  translator.clear();
  // 更新 翻译语言
  TUIChatService.setTranslationLanguage(lang);
  // 同步本地设置
  settingList.value.translateLanguage.selectedChild = lang;
  // 关闭展示
  settingList.value.translateLanguage.showChildren = false;
}
</script>

<style lang="scss" scoped src="../../styles/profile/index.scss"></style>
